<div class="cart">
<script type="text/javascript">
    var quantities=Array();

    function getQuantity(id){

        for (var i=0;i<quantities.length;i++)
        {
            if (quantities[i].id==id) return quantities[i].quantity;
        }
        return null;
    }
</script>
<?php


$catalogueUrl=$portlet_shop_cart_catalogueUrl;
if ($catalogueUrl==null) $catalogueUrl="catalogue";

if (!isset($app_shop_discount)) {
    $app_shop_discount=0;
    ShowError($var_shop_discountundefined);
}

$discount=$app_shop_discount; //$portlet_shop_cart_Discount; //50dh
$clientId=getShopClientId();


if (getParameter("action")=="validate_cart" && isset($_SESSION['panier']))
{


	
	if (!$clientId)
	{
		header("Location: ".createUrl("pageName","login","action","login","backurl",encryptUrl(curPageURI())));
		exit;
	}

    //calculate price


    $total=0;
    for($i = 0; $i < count($_SESSION['panier']['unitId']); $i++)
    {

        $id=$_SESSION['panier']['unitId'][$i];

        if ($app_shop_hasUnit=="yes")
        {
            $sSql="SELECT
shop_articles.price
FROM
shop_articles
INNER JOIN shop_unit ON shop_articles.id = shop_unit.articleId
WHERE
shop_unit.id = ".$id." AND
shop_articles.portalId = ".$portalId;
        }else{
            $sSql="SELECT
				shop_articles.price
				FROM
				shop_articles
				WHERE
				shop_articles.id = ".$id." AND
				shop_articles.portalId = ".$portalId;

        }
        //	echo $sSql;
        Portal_log($sSql);
        $rs=$GLOBALS["conn"]->Execute($sSql);
        $price=$rs->fields["price"];

        $quantity=$_SESSION['panier']['quantity'][$i];


        $total+=$price*$quantity;


    }

	// is devis
	
	$isdevis=false;
	$nature="Y";
	
		$action="validate_cart_success";	
	if (getParameter("devis")=="true") {
		$isdevis=true;
		$nature="D";
		
		$action="validate_devis_success";
	}
	
	//persister la commande
	
	$order_discount=0;
	$ref="W".date("siHdmY");
	$sSql="INSERT INTO shop_order (portalId,clientId,fromweb,date,ref,orderstatusId,discount) values (".$portalId.",".$clientId.",'".$nature."','".ew_CurrentDateTime()."','".$ref."',".getStatusIdByCode("AP").",".$order_discount.")";
	$GLOBALS["conn"]->Execute($sSql);
	//echo $sSql;

	$orderId=getLastId();
	//command line
	for($i = 0; $i < count($_SESSION['panier']['unitId']); $i++)
	{
		if ($app_shop_hasUnit=="yes")
		{
		$unitId=$_SESSION['panier']['unitId'][$i];
		$articleId=getArticleIdByUnitId($unitId);
		}else{
			$articleId=$_SESSION['panier']['unitId'][$i];
			$unitId="'NULL'";
		}
		$quantity=$_SESSION['panier']['quantity'][$i];//".getSizeIdByUnitId($unitId).", ,".getDefaultPictureByUnitId($unitId)."
		$sSql="INSERT INTO shop_orderline (quantity,orderId,articleId,unitId) values (".$quantity.",".$orderId.",".$articleId.",".$unitId.")";

		//echo $sSql;
		$GLOBALS["conn"]->Execute($sSql);
	}

if (!$isdevis) {
	
	
	 $order_discount=getShopDiscount($total,$discount,getPromos($clientId));
    $total-=$order_discount;
	 
	$sSql="UPDATE shop_order SET discount=".$order_discount." WHERE id=".$orderId;
	//echo $sSql;
	$GLOBALS["conn"]->Execute($sSql);
	
	
		//diminuer les quantités
		// remise a zero promo pour le client (une seul fois)
$sSql="UPDATE shop_clients SET promo=0 WHERE id=".$clientId;
//echo $sSql;
$GLOBALS["conn"]->Execute($sSql);		

		
		
			
		// id parrain

			$sSql = "SELECT parrain FROM shop_clients where id=".$clientId;
			//echo $sSql;
			$rs=$GLOBALS["conn"]->Execute($sSql);
			$parrainId=$rs->fields["parrain"];
			
			
			//ajouter une promo si il est parrainé 50
			// incrémentation promo parrain (une seul fois) si existe 50
			$sSql="UPDATE shop_clients SET promo=".(getPromos($parrainId)+1)." WHERE id=".$parrainId;
			//echo $sSql;
			$GLOBALS["conn"]->Execute($sSql);

		

		
}
$price=getShopOrderPrice($orderId);
$sSql="UPDATE shop_order SET total=".$total." WHERE id=".$orderId;
//echo $sSql;
$GLOBALS["conn"]->Execute($sSql);

header("Location: ".createNiceUrl("pageName","client_area","action",$action,"orderId",$orderId));
}


?>

<!--<div class="title"><?php echo $var_shop_yourcart; ?></div>-->
<form action="<?php echo createNiceUrl("pageName",getParameter("pageName")); ?>" method="POST">

<?php 

//echo $app_shop_hasUnit;
$i=0;
$articleId=getParameter("articleId");
$quantity=getParameter("quantity");
$size=getParameter("size");
$unitId=null;

while (getParameter("unitId_".$i))
{
	$unitId=getParameter("unitId_".$i);
	$quantity=getParameter("quantity_".$unitId);
	modifierQTeArticle($unitId,$quantity);
	if (getParameter("delete_".$unitId)=="on") supprimerArticle($unitId);
//echo "<b>".$unitId." ".getParameter("delete_".$unitId)."</b><br/>";
$i++;
}

	


if (getcartCount()==0) supprimePanier();


if ($articleId)
{

	if ($app_shop_hasUnit=="yes")
	{
        if (getParameter("unit")==null){
$sSql="SELECT shop_unit.id
FROM
shop_unit
INNER JOIN shop_sizes ON shop_unit.size = shop_sizes.id
WHERE
shop_unit.articleId = ".$articleId." AND
shop_sizes.size = ".$size;


//echo $sSql;
Portal_log($sSql);
$rs=$GLOBALS["conn"]->Execute($sSql);
if (!$rs) ShowError($var_shop_noitemselected);
else{
$unitId=$rs->fields["id"];
}


    } else{

        $unitId=getParameter("unit");
        $size=null;
    }




if ($unitId) ajouterArticle($unitId, $quantity, $size);





    }else{
	
	ajouterArticle($articleId, $quantity, $size);
}


}

if (isset($_SESSION['panier'])){
	
	?>
	<div class="top">
</div>
	<table width="100%">
<tr class="toptable">

<td width="15px"></td>
    <td></td>
<td><?php echo $var_shop_item;?></td>
<?php if ($app_shop_hasUnit=="yes")
			{
			?>
		<td><?php echo $var_shop_ShoeSize; ?></td>
		<?php } ?>

<td><?php echo $var_shop_Quantity; ?></td>
    <?php if ($portlet_shop_cart_ShowReference!="no") { ?>
<td><?php echo $var_shop_Reference; ?></td>
    <?php } ?>
<td><?php echo $var_shop_Price; ?></td>
<td ><?php echo $var_shop_Subtotal; ?></td>
<td style="width: 72px;"><?php echo $var_shop_Remove; ?></td>
    <td width="15px"></td>
</tr>
<?php 
$total=0;
for($i = 0; $i < count($_SESSION['panier']['unitId']); $i++)
		{
		
			$id=$_SESSION['panier']['unitId'][$i];
			
			if ($app_shop_hasUnit=="yes")
			{
			$sSql="SELECT
shop_gallery.picture,
shop_articles.price,
shop_articles.lib_$LANG as lib,
shop_articles.id,
shop_articles.reference,
shop_unit.availability,
shop_unit.lib as unitlib
FROM
shop_articles
INNER JOIN shop_unit ON shop_articles.id = shop_unit.articleId
INNER JOIN shop_gallery ON shop_articles.id = shop_gallery.articleId
WHERE
shop_gallery.`default` = 'Y' AND
shop_unit.id = ".$id." AND
shop_articles.portalId = ".$portalId;
			}else{
				$sSql="SELECT
				shop_gallery.picture,
				shop_articles.price,
				shop_articles.lib_$LANG as lib,
				shop_articles.id,
				shop_articles.availability,
				shop_articles.reference
				FROM
				shop_articles
							INNER JOIN shop_gallery ON shop_articles.id = shop_gallery.articleId
				WHERE
				shop_gallery.`default` = 'Y' AND
				shop_articles.id = ".$id." AND
				shop_articles.portalId = ".$portalId;
				
			}
		//	echo $sSql;
			Portal_log($sSql);
			$rs=$GLOBALS["conn"]->Execute($sSql);
			$price=$rs->fields["price"];
			$articleId=$rs->fields["id"];
			$lib=$rs->fields["lib"];
			//$availability=$rs->fields["availability"];
			$reference=$rs->fields["reference"];
            $availability=$rs->fields["availability"];
			$quantity=$_SESSION['panier']['quantity'][$i];
			$class="odded";
			if ($i%2) $class="even";
			?>
			<tr class="line <?php echo $class; ?>" id="article_<?php echo $id; ?>">
			<td></td>
            <td>
                <?php if ($availability>2) { ?>

                <img src="/images/icons/instock.png"/>
                <?php } elseif ($availability<=2) { ?>
                <img src="/images/icons/inoutofstock.png"/>
                <?php } else { ?>
                <img src="/images/icons/outofstock.png"/>
                <?php } ?>
            </td>
			<td>
		<a href="<?php echo createNiceUrl("pageName","article","articleId",$articleId); ?>"><?php echo $lib; ?></a>
		
			<!--<div  id="image_<?php echo $id; ?>" class="image">
			<img src="<?php echo getFilesPath("gallery",false)."/".$rs->fields["picture"]; ?>" width="120px" height="120px" />
			
			</div>-->
			</td>
		<?php if ($app_shop_hasUnit=="yes")
			{
			?>
		<td><?php
            if ($app_shop_hasSize=="yes"){
            echo $_SESSION['panier']['size'][$i];
            }else{
            echo $rs->fields["unitlib"];
            }

            ?></td>
		<?php } ?>
			<td>
			<input type="hidden" name="unitId_<?php echo $i; ?>" value="<?php echo $id; ?>">
			<input class="quantity" type="text" id="quantity_<?php echo $id; ?>" name="quantity_<?php echo $id; ?>" value="<?php echo $quantity; ?>" />
                <input type="button" value="+" id="inc_<?php echo $id; ?>"><input type="button" value="-" id="dec_<?php echo $id; ?>">

                <script type="text/javascript">

                    quantities.push({id:<?php echo $id; ?>,quantity:<?php echo $availability; ?>})

                </script>


			  <script type="text/javascript">
//  $("#quantity_<?php echo $id; ?>").spinner({min:1,max:999,stepping: 1});
  </script>
			</td>
            <?php if ($portlet_shop_cart_ShowReference!="no") { ?>
<td><?php echo $reference; ?></td>
                <?php } ?>
<td><div  class="pricetag">
    <?php  if ($rs->fields["price"]!="" || $rs->fields["price"]>0) { ?>
    <?php echo formatMoney($price,true); ?> <?php echo $app_shop_currency; ?>
    <?php }else{ ?>
    N/A
    <?php } ?></div>
        </td>

<td ><div class="pricetag">
    <?php  if ($rs->fields["price"]!="" || $rs->fields["price"]>0) { ?>
    <?php echo formatMoney($price*$quantity,true); ?> <?php echo $app_shop_currency; ?>
    <?php }else{ ?>
    N/A
    <?php } ?>
</div>
    </td>
			
			
				<td><input type="checkbox" name="delete_<?php echo $id; ?>"/> </td>
                <td width="15px"></td>
			</tr>
			<?php 
			
			$total+=$price*$quantity;
			
			
		}
?>
</table>
<div class="bottom">
</div>
<div class="total">
<div><?php echo $var_shop_Total; ?> : <div class="pricetag" ><?php echo formatMoney($total,true); ?> <?php echo $app_shop_currency; ?></div></div>
<?php 

// check promotions



$promos=getPromos($clientId);



$order_discount=0;
if ($promos>0 && $clientId && $discount>0){
	
	
	$order_discount=getShopDiscount($total,$discount,$promos);
	
?>
<div><?php echo $var_shop_discount; ?> : <div class="pricetag" ><?php echo $order_discount; ?> <?php echo $app_shop_currency; ?></div></div>
<?php } ?>
<div class="topay"><?php echo $var_shop_sumtopay; ?> : <div class="pricetag" ><?php echo formatMoney($total-$order_discount,true); ?> <?php echo $app_shop_currency; ?></div></div>
</div>
<br clear="all" />
<div class="buttons">
<input type="button" onclick="self.location.href='<?php echo createNiceUrl("pageName",$catalogueUrl); ?>'" value="<?php echo $var_shop_resumeshopping; ?>" name="<?php echo $portletUID; ?>submit" class="button"/>
<input type="submit" value="<?php echo $var_shop_updatecart; ?>" name="<?php echo $portletUID; ?>submit" class="button"/>
<input type="button"  onclick="self.location.href='<?php echo createNiceUrl("pageName",getParameter("pageName"),"action","validate_cart","devis","true"); ?>'" value="<?php echo $var_shop_quotationrequest; ?>" name="<?php echo $portletUID; ?>submit" class="button"/>
<input type="button"  onclick="self.location.href='<?php echo createNiceUrl("pageName",getParameter("pageName"),"action","validate_cart","devis","false"); ?>'" value="<?php echo $var_shop_submitorder; ?>" name="<?php echo $portletUID; ?>submit" class="button"/>
</div>
<?php }

else{?>
    <?php echo $var_shop_cartisempty; ?>
<?php }?>
</form>
</div>


<script type="text/javascript">


$('tr[id^="article_"]').click(
		  function () {
			  $('div[id^="image_"]').hide();
			 var id=$(this).attr('id').replace("article_","");
			   $("#image_"+id).fadeIn();
			  }
			);






$('input[id^="inc_"]').click(function() {
    var id=$(this).attr('id').replace("inc_","");
    c=$("#quantity_"+id).val();

    if (c<getQuantity(id)){


        $("#quantity_"+id).val(++c);}

});
$('input[id^="dec_"]').click(function() {
    var id=$(this).attr('id').replace("dec_","");

    if ($("#quantity_"+id).val()>=1){
        $("#quantity_"+id).val( $("#quantity_"+id).val()-1);}

});
	</script>